package com.xkstream.client.ui.live.fragment;

import android.app.Dialog;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nimlib.sdk.chatroom.constant.MemberType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.xkstream.client.R;
import com.xkstream.client.api.ChatroomService;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.BaseFragment;
import com.xkstream.client.entity.Gift;
import com.xkstream.client.entity.User;
import com.xkstream.client.entity.kt.GiftStarData;
import com.xkstream.client.nim.BetRankAndNumAttachment;
import com.xkstream.client.nim.EnterChatRoomCallback;
import com.xkstream.client.nim.GifAttachment;
import com.xkstream.client.nim.NimHelper;
import com.xkstream.client.nim.OnMessageReceiveListener;
import com.xkstream.client.nim.ResultAttachment;
import com.xkstream.client.presenter.kt.ChatroomContract;
import com.xkstream.client.presenter.kt.ChatroomPresenter;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.ui.adapter.ChatRoomAdapter_V2;
import com.xkstream.client.ui.live.LiveRoomActivity_V2;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.videothumbloader.cache.WeakRefrenceCache;
import com.xkstream.client.view.CircleImageView;
import com.xkstream.client.view.gift.GiftShowManager;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017-10-11.
 */
@Deprecated
public class ChatroomFragment extends BaseFragment<ChatroomContract.Presenter> implements OnMessageReceiveListener,
        ChatroomContract.View {
    @BindView(R.id.tv_bulletin)
    TextView tvBulletin;
    @BindView(R.id.recycler_chat)
    RecyclerView recyclerChat;
    @BindView(R.id.llGift)
    LinearLayout llGift;
    @BindView(R.id.root)
    LinearLayout rootLayout;
    @BindView(R.id.layout_gift_star)
    View layoutGiftStart;
    @BindView(R.id.layout_bell_star)
    View layoutBellStart;

    @BindView(R.id.bellStar)
    TextView tvBellStar;
    @BindView(R.id.giftStar)
    TextView tvGiftStar;

    @BindView(R.id.llBellStar)
    LinearLayout llBellStar;

    ChatRoomAdapter_V2 chatAdapter;

    List<Object> mMessages = new ArrayList<>();

    LinearLayoutManager layoutManager;
    @BindView(R.id.tvName1)
    TextView tvName1;
    @BindView(R.id.tvName2)
    TextView tvName2;
    @BindView(R.id.tvName3)
    TextView tvName3;
    @BindView(R.id.tvName4)
    TextView tvName4;
    @BindView(R.id.tvName5)
    TextView tvName5;
    @BindView(R.id.tvName6)
    TextView tvName6;
    @BindView(R.id.tvName7)
    TextView tvName7;
    @BindView(R.id.tvName8)
    TextView tvName8;
    @BindView(R.id.tvName9)
    TextView tvName9;
    private String chatroomId;
    private int gameType;

    @BindView(R.id.rlStarDes)
    RelativeLayout rlStarDes;
    @BindView(R.id.tvStarDes)
    TextView tvStarDes;

    @BindView(R.id.ivHeader)
    CircleImageView ivHeader;
    @BindView(R.id.tvNickname)
    TextView tvNickName;
    @BindView(R.id.tvViewCount)
    TextView tvViewCount;


    @BindString(R.string.viewer_count)
    String strViewCount;

    private Dialog commentDialog;

    private GiftShowManager giftShowManager;

    private static final int CODE_GIFTSTAR = 0X1001;


    private List<GiftStarData.GiftStar> giftStarList;

    private MHandler mHandler;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chatroom;
    }

    @Override
    public void initViews(View root) {
        chatroomId = getArguments().getString("chatroomId");
        gameType = getArguments().getInt("gameType");
        initAnchor();
        presenter = new ChatroomPresenter(this);
        layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        recyclerChat.setLayoutManager(layoutManager);

        chatAdapter = new ChatRoomAdapter_V2(mActivity, mMessages);
        recyclerChat.setAdapter(chatAdapter);

        chatAdapter.setOnItemClickListener((v, p) -> {
            ChatRoomMessage msg = (ChatRoomMessage) mMessages.get(p);
            queryMemberByMessage(msg);
        });

        enterChatRoom();

        giftShowManager = new GiftShowManager(mActivity, llGift);
        giftShowManager.showGift();

        recyclerChat.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP
                    && event.getX() > (DeviceUtils.deviceWidth(mActivity) / 2)
                    ) {
                hideStarLayout();
            }
            return false;
        });
        registerRxBus();
        mHandler = new MHandler(this);
        mHandler.sendEmptyMessageDelayed(CODE_GIFTSTAR,1000);
    }

    private void initAnchor(){
        tvViewCount.setText(String.format(strViewCount,0));
        AsyncImage.loadPhoto(mActivity,getArguments().getString("head"),ivHeader);
        tvNickName.setText(getArguments().getString("nickname"));
    }

    //根据message查询聊天室成员
    private void queryMemberByMessage(ChatRoomMessage msg) {
        NimHelper.getChatRoomMember(chatroomId, members -> {
            if (members == null || members.size() == 0) {
                showToast(R.string.user_not_exist);
            } else {
                createCommnetClickDialog(members.get(0), msg.getFromAccount());
            }
        }, msg.getFromAccount());
    }

    private void registerRxBus() {
        Rxbus.getDefault().register(String.class)
                .subscribe((s) -> {
                    if (s.equals("onclick")) {
                        hideStarLayout();
                    } else if (s.equals("dismiss")) {
                        commentDialog.dismiss();
                    }
                });
    }

    private void hideStarLayout() {
        if (layoutGiftStart==null)return;
        if (layoutGiftStart.getVisibility() == View.VISIBLE) {
            layoutGiftStart.setVisibility(View.GONE);
        }
        if (layoutBellStart.getVisibility() == View.VISIBLE) {
            layoutBellStart.setVisibility(View.GONE);
        }
        if (rlStarDes.getVisibility() == View.VISIBLE) {
            rlStarDes.setVisibility(View.GONE);
        }
        tvGiftStar.setVisibility(View.VISIBLE);
        tvBellStar.setVisibility(View.VISIBLE);

    }

    private void enterChatRoom() {
        NimHelper.enterChatRoom(chatroomId, new EnterChatRoomCallback() {
            @Override
            public void enterSuccess(Object param) {
                LogUtil.e(TAG, "enterSuccess");
            }

            @Override
            public void enterFaild(int code) {
                LogUtil.e(TAG, "enterFaild");
            }

            @Override
            public void enterException(Throwable e) {
                LogUtil.e(TAG, "enterException");
            }
        });
        NimHelper.registerMsgObserver(this, true);
    }

    @Override
    public void onReceive(ChatRoomMessage message) {
        LogUtil.e(TAG, "onReceive " + message.toString());
        MsgAttachment attachment = message.getAttachment();
        if (attachment instanceof ResultAttachment) {

        } else if (attachment instanceof ChatRoomNotificationAttachment) {
            ChatRoomNotificationAttachment notificationAttachment = (ChatRoomNotificationAttachment) attachment;
            if (notificationAttachment.getType() == NotificationType.ChatRoomMemberIn
                    || notificationAttachment.getType() == NotificationType.ChatRoomManagerAdd
                    || notificationAttachment.getType() == NotificationType.ChatRoomManagerRemove
                    || notificationAttachment.getType() == NotificationType.ChatRoomMemberTempMuteAdd) {
                if (notificationAttachment.getOperator().equals(
                        Application.getUser().getUser_code()
                )){
                    return;
                }
                mMessages.add(message);
                chatAdapter.notifyDataSetChanged();
                if (recyclerChat!=null)
                recyclerChat.scrollToPosition(chatAdapter.getItemCount() - 1);
            }
        } else if (attachment instanceof BetRankAndNumAttachment) {

        } else if (attachment instanceof GifAttachment) {
            GifAttachment giftAttachment = (GifAttachment) attachment;
            Gift gift = new Gift();
            gift.setName(giftAttachment.getGiftName());
            gift.setUserId(giftAttachment.getSenderName());
            gift.setNum(giftAttachment.getGiftNum());
            gift.setNoFrameIcon(giftAttachment.getGiftShowImage());
            giftShowManager.addGift(gift);

            mMessages.add(message);
            chatAdapter.notifyDataSetChanged();
            recyclerChat.scrollToPosition(chatAdapter.getItemCount() - 1);

        } else {
            mMessages.add(message);
            chatAdapter.notifyDataSetChanged();
            recyclerChat.scrollToPosition(chatAdapter.getItemCount() - 1);
        }

    }

    @OnClick({R.id.bellStar, R.id.giftStar,
            R.id.recycler_chat, R.id.llGift, R.id.v_cover,
            R.id.iv_bell_help, R.id.iv_help_gift})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bellStar:
                layoutBellStart.setVisibility(View.VISIBLE);
                tvBellStar.setVisibility(View.GONE);
                tvGiftStar.setVisibility(View.GONE);
//                playAnim(v);
                break;
            case R.id.giftStar:
                layoutGiftStart.setVisibility(View.VISIBLE);
                tvBellStar.setVisibility(View.GONE);
                tvGiftStar.setVisibility(View.GONE);
//                playAnim(v);
                break;

            case R.id.llGift:
            case R.id.v_cover:
            case R.id.recycler_chat:
                hideStarLayout();
                break;
            case R.id.iv_bell_help:
                setStarDes(false);
                break;

            case R.id.iv_help_gift:
                setStarDes(true);
                break;


        }
    }

    private void addBellItem(int index, String name) {
        if (llBellStar.getChildAt(0) instanceof TextView) {
            llBellStar.removeAllViews();
        }
        int count = llBellStar.getChildCount();
        if (count < 3) {
            View item = View.inflate(getContext(), R.layout.layout_bell_star_item, null);
            TextView tvName = (TextView) item.findViewById(R.id.tvName);
            tvName.setText(name);
            if (index > count) {
                index = count;
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, DeviceUtils.dp2px(getContext(), 5),
                    0, DeviceUtils.dp2px(getContext(), 5));
            llBellStar.addView(item, index, params);
        } else {
            View item = llBellStar.getChildAt(index);
            TextView tvName = (TextView) item.findViewById(R.id.tvName);
            tvName.setText(name);
        }
    }

    private void setGiftStarItem(int index, String name) {
        String tag = "tvName" + (index + 1);
        TextView view = (TextView) root.findViewWithTag(tag);
        view.setText(name);
    }

    private void setStarDes(boolean isGift) {
        rlStarDes.setVisibility(View.VISIBLE);
        if (isGift) {
            tvStarDes.setText(Html.fromHtml(getResources().getString(R.string.gift_star_des)));
        } else {
            tvStarDes.setText(Html.fromHtml(getResources().getString(R.string.bell_star_des)));
        }
    }

    private void playAnim(View view) {
        if (view.getVisibility()==View.GONE)return;
        Animation anim = new TranslateAnimation(0, 0, 0, view.getWidth() * 0.1f);
        CycleInterpolator interpolator = new CycleInterpolator(2);
        anim.setDuration(1000);
        anim.setInterpolator(interpolator);
        view.startAnimation(anim);
    }

    private void createCommnetClickDialog(ChatRoomMember member, final String userId) {
        View view = View.inflate(getContext(), R.layout.layout_chatroomhandle_dialog, null);
        ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
        TextView tvShutUp = (TextView) view.findViewById(R.id.tvShutUp);
        TextView tvSetAdmin = (TextView) view.findViewById(R.id.tvSetAdmin);
        ImageView ivHeader = (ImageView) view.findViewById(R.id.ivHeader);
        TextView tvUserName = (TextView) view.findViewById(R.id.tvUserName);
        commentDialog = new Dialog(getContext(), R.style.Theme_Transparent);
        commentDialog.setContentView(view);
        commentDialog.show();
        String avatar = member.getAvatar();
        String nickName = member.getNick();
        int memberType = member.getMemberType().getValue();
        if (memberType == MemberType.ADMIN.getValue()) {
            tvSetAdmin.setText(R.string.remove_admin);
            tvSetAdmin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setAdmin(userId);
                }
            });
        } else if (memberType == MemberType.GUEST.getValue() || memberType == MemberType.LIMITED.getValue() || memberType == MemberType.NORMAL.getValue()) {
            tvSetAdmin.setText(R.string.set_admin);
            tvSetAdmin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setAdmin(userId);
                }
            });
        } else if (memberType == MemberType.CREATOR.getValue()) {
            tvSetAdmin.setText(R.string.anchor);
        } else {
            tvSetAdmin.setText(R.string.unknow);
        }
        if (memberType != MemberType.ADMIN.getValue()) {
            tvShutUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shutUp(userId);
                }
            });
        }
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentDialog.dismiss();
            }
        });
        if (avatar.contains(".")) {
            AsyncImage.loadPhoto(getContext(), avatar, ivHeader);
        } else {
            Bitmap head = getHead(TextUtils.isEmpty(avatar) ? "1" : avatar);
            ivHeader.setImageBitmap(head);
        }


        if (TextUtils.isEmpty(nickName)) {
            tvUserName.setText("");
        } else {
            tvUserName.setText(nickName);
        }
    }

    private void setAdmin(String userId) {
        User user = Application.getUser();
        Map<String, Object> params = new HashMap<>();
        params.put("operator", user.getUser_code());
        params.put("roomid", chatroomId);
        params.put("user_code", userId);
        ((LiveRoomActivity_V2) getActivity()).setAdmin(params);
    }

    private void shutUp(String userId) {
        User user = Application.getUser();
        Map<String, Object> params = new HashMap<>();
        params.put("operator", user.getUser_code());
        params.put("roomid", chatroomId);
        params.put("target", userId);
        params.put("muteDuration", 86400 + "");
        ((LiveRoomActivity_V2) getActivity()).chatroomMute(params);
    }

    private Bitmap getHead(String id) {
        AssetManager manager = getActivity().getAssets();
        InputStream ios = null;
        try {
            ios = manager.open("head/" + id + ".jpg");
            return BitmapFactory.decodeStream(ios);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ios != null) {
                    ios.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void showRankGiftStar(@NotNull BaseData<GiftStarData> data) {
        GiftStarData giftStarData = data.getData();
        if (giftStarData != null && giftStarData.getRankList() != null &&
                giftStarData.getRankList().size() > 0) {
            List<GiftStarData.GiftStar> starList = giftStarData.getRankList();
            sortGiftStarList(starList);
        }
    }

    int index = 0;

    private void sortGiftStarList(List<GiftStarData.GiftStar> list) {
        index++;
        if (index%4==0){
           // test(list);
        }
        LogUtil.e(TAG,list.toString());
        if (giftStarList==null){
            giftStarList = list;
            for (int i = 0; i < giftStarList.size(); i++) {
                setGiftStarItem(i, giftStarList.get(i).getNickname());
            }
            playAnim(tvGiftStar);
        }else {
            List<GiftStarData.GiftStar> tmp = giftStarList;

            if (!tmp.equals(list)) {
                giftStarList = list;
                for (int i = 0; i < giftStarList.size(); i++) {
                    setGiftStarItem(i, giftStarList.get(i).getNickname());
                }
                playAnim(tvGiftStar);
            }
        }

    }

    private void test(List<GiftStarData.GiftStar> list) {
        for (int i = 0; i < list.size(); i++) {
            GiftStarData.GiftStar giftStar = list.get(i);
            giftStar.setNickname(giftStar.getNickname() + "_test");
            list.set(i, giftStar);
        }
    }

    @Override
    public void setPresenter(ChatroomContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    private static class MHandler extends Handler {
        WeakReference<ChatroomFragment> reference;

        public MHandler(ChatroomFragment fragment) {
            this.reference = new WeakReference<ChatroomFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_GIFTSTAR:
                    removeMessages(CODE_GIFTSTAR);
                    if (reference.get() != null) {
                        reference.get().getRankGiftStar();
                        sendEmptyMessageDelayed(CODE_GIFTSTAR,5000);
                    }

                    break;
            }
        }
    }

    private void getRankGiftStar() {
        Map<String, String> params = new HashMap<>();
        String userCode = Application.getUser().getUser_code();
        params.put("anchor_user_code", userCode);
        presenter.getRankGiftStar(params);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacksAndMessages(null);
    }
}